package com.wnxy.sddfp.common.exception;

import com.wnxy.sddfp.common.result.Result;
import com.wnxy.sddfp.common.result.enums.impl.ResultCode;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalException {

    /**
     * 处理系统业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result handlerBusinessException(BusinessException e){
        e.printStackTrace();
        return Result.fail(e.getErrorCode());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handlerMethodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        Map<String, String> errorMap = e.getBindingResult().getFieldErrors().stream().collect(
                Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
        return Result.fail(errorMap);
    }

    /**
     * 处理Exception类型的异常
     */
    @ExceptionHandler(Exception.class)
    public Result handlerException(Exception e){
        e.printStackTrace();
        return Result.fail(ResultCode.FAILED);
    }
}